package com.it.orderservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.commonutils.JwtUtils;
import com.it.commonutils.R;
import com.it.orderservice.entity.Order;
import com.it.orderservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author test.java
 * @since 2021-04-22
 */
@RestController
@RequestMapping("/orderservice/order")
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    //生成订单方法
    @PostMapping("createOrder/{courseId}")
    //登录之后用户信息放到cookie中，前端写了拦截器，信息放到了cookie中的head中，
    // 使用HttpServletRequest取到head中的用户信息
    //jwt工具类传入request对象  从head中取到token字符串 解析返回用户id
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request){
        //返回订单号
        String orderNo= orderService.createOrders(courseId, JwtUtils.getMemberIdByJwtToken(request));
        return R.ok().data("orderId",orderNo);
    }

    //根据订单号查询订单信息
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId){
        //根据订单号查数据库  唯一对应的订单 需要条件
        QueryWrapper<Order>wrapper=new QueryWrapper<Order>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item",order);
    }

    //根据课程id和用户id查询订单状态
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId){
        QueryWrapper<Order>wrapper=new QueryWrapper<Order>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        if(count>0){
            return true;
        }else{
            return false;
        }

    }
}

